package util;

import exception.CookieErrorException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author 石小俊
 * @date 2023年10月24日 10:21
 */
public class CookieUtil {

    public static void addCookie(String name, String value, HttpServletResponse response) {
        try {
            Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new CookieErrorException("添加cookie出错");
        }
    }

    public static void addCookie(String name, String value, int maxAge, HttpServletResponse response) {
        try {
            Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
            cookie.setMaxAge(maxAge);
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new CookieErrorException("添加cookie出错");
        }
    }

    public static void deleteCookie(String name, HttpServletResponse response) {
        addCookie(name, "", 0, response);
    }

    public static void modifyCookie(String name, String value, HttpServletResponse response) {
        addCookie(name, value, response);
    }

    public static void modifyCookie(String name, String value, int maxAge, HttpServletResponse response) {
        addCookie(name, value, maxAge, response);
    }

    public static String findByName(String name, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        try {
            if(cookies != null && cookies.length != 0){
                for(Cookie cookie : cookies){
                    if(name.equals(cookie.getName())){
                        return URLDecoder.decode(cookie.getValue(),"UTF-8");
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new CookieErrorException("获取Cookie出错");
        }
        return null;
    }
}
